package org.example.rzfx.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.rzfx.dto.AlarmHandleDTO;
import org.example.rzfx.dto.Result;
import org.example.rzfx.entity.Alarm;
import org.example.rzfx.entity.AlarmRule;
import org.example.rzfx.service.AlarmService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * 告警控制器
 */
@RestController
@RequestMapping("/api/alarm")
@CrossOrigin
public class AlarmController {
    
    @Resource
    private AlarmService alarmService;
    
    /**
     * 查询未处理告警
     */
    @GetMapping("/unhandled")
    public Result<List<Alarm>> getUnhandledAlarms() {
        List<Alarm> alarms = alarmService.getUnhandledAlarms();
        return Result.success(alarms);
    }
    
    /**
     * 查询告警列表（分页）
     */
    @GetMapping("/list")
    public Result<?> listAlarms(@RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(defaultValue = "20") Integer pageSize) {
        Page<Alarm> page = new Page<>(pageNum, pageSize);
        return Result.success(alarmService.page(page));
    }
    
    /**
     * 处理告警
     */
    @PostMapping("/handle")
    public Result<Void> handleAlarm(@Valid @RequestBody AlarmHandleDTO handleDTO) {
        try {
            alarmService.handleAlarm(handleDTO);
            return Result.success("处理成功", null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 查询告警详情
     */
    @GetMapping("/{id}")
    public Result<Alarm> getAlarmDetail(@PathVariable Long id) {
        Alarm alarm = alarmService.getById(id);
        if (alarm == null) {
            return Result.error("告警记录不存在");
        }
        return Result.success(alarm);
    }
    
    /**
     * 手动触发告警检查（仅管理员）
     */
    @PostMapping("/check")
    @SaCheckRole("1")
    public Result<Void> checkAlarmRules() {
        try {
            alarmService.checkAlarmRules();
            return Result.success("检查完成", null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}

